

//
//  ScanViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/9.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AFNetworking.h"
#import "EquipmentViewController.h"
#import "HistoryViewController.h"
#import "SeekEquipmentViewController.h"
@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureDevice *device;
//设备输入类 用来表示输入数据的硬件设备，配置抽象设备的port
@property (nonatomic, strong) AVCaptureDeviceInput *input;
// 输出类。这个支持二维码、条形码等图像数据的识别
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
// 会话对象。此类作为硬件设备输入输出信息的桥梁，承担实时获取设备数据的责任
@property (nonatomic, strong) AVCaptureSession *session;
//图层类。用来快速呈现摄像头获取的原始数据 二维码扫描功能的实现步骤是创建好会话对象，用来获取从硬件设备输入的数据，并实时显示在界面上
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIView *lineView;
//设备类型文字
@property (nonatomic, strong) NSString *typeNum;

@end

@implementation ScanViewController



- (void)initView
{
    [super initView];
    [self.navBar setHidden:YES];
    self.navBar.leftView = nil;
    self.navBar.bgColor =[UIColor clearColor];
    self.hide=YES;
    UIView *narView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 64)];
    narView.backgroundColor =[UIColor clearColor];
    [self.view addSubview:narView];
    
    UIView *backView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 64)];
    [narView addSubview:backView];
    [backView bk_whenTapped:^{
        [self backController];
    }];

    UIImage *icoBack = [UIImage imageNamed:@"Ico_nar_backWhite"];
    UIImageView *imgBack = [[UIImageView alloc] initWithFrame:CGRectMake(15, 33, icoBack.size.width, icoBack.size.height)];
    imgBack.image=icoBack;
    [backView addSubview:imgBack];
    
    UILabel *backTitle = [[UILabel alloc] init];
    backTitle.frame=CGRectMake(CGRectGetMaxX(imgBack.frame) + 5, 20, 50 - imgBack.frame.size.width,44);

    [backTitle setText:@"返回"];
    [backTitle setTextColor:[UIColor whiteColor]];
    [backTitle setFont:F(14)];
    [backView addSubview:backTitle];
 
    UILabel *titleLab =[[UILabel alloc]init];
    [narView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(narView);
        make.top.equalTo(narView).offset(30);
    }];
    titleLab.font =F(16);
    titleLab.textColor =[UIColor whiteColor];
    
    ///有报修单从详情跳过来 有手动输入
    if (self.dataType==HasListData) {
       
        titleLab.text=@"补充设备";
      
    }else
    {
        //从首页进来时候没有手动输入
        titleLab.text=@"查询设备";

        
    }
    
    float width = [UIScreen mainScreen].bounds.size.width;
    float height = [UIScreen mainScreen].bounds.size.height;
    
    
    CGSize size = CGSizeMake(MAX(width, height), MAX(width, height));
    UIView *bgview = [[UIView alloc] initWithFrame:CGRectMake(width / 2 - size.width / 2, height / 2 - size.height / 2, size.width, size.height)];
    [self.view addSubview:bgview];
    [self.view sendSubviewToBack:bgview];
    [self.view.layer setMasksToBounds:YES];
    [bgview setBackgroundColor:[UIColor clearColor]];
    [bgview.layer setBorderColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.6].CGColor];
    [bgview.layer setBorderWidth:MAX(width, height) / 2 - (width - 80) / 2];
    
    UIImage *imgrt = [UIImage imageNamed:@"Ico_Scan_Jiao"];
    UIImageView *jiaortview = [[UIImageView alloc] initWithImage:imgrt];
    UIImageView *jiaoltview = [[UIImageView alloc] initWithImage:imgrt];
    jiaoltview.transform = CGAffineTransformScale(jiaoltview.transform, -1.0, 1.0);
    UIImageView *jiaolbview = [[UIImageView alloc] initWithImage:imgrt];
    jiaolbview.transform = CGAffineTransformScale(jiaolbview.transform, -1.0, 1.0);
    jiaolbview.transform = CGAffineTransformScale(jiaolbview.transform, 1.0, -1.0);
    UIImageView *jiaorbview = [[UIImageView alloc] initWithImage:imgrt];
    jiaorbview.transform = CGAffineTransformScale(jiaorbview.transform, 1.0, -1.0);
    
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(40, height / 2 - width / 2 + 40, width - 80, 2)];
    [self.view addSubview:_lineView];
    [_lineView setBackgroundColor:C(@"6dc2e8")];

    [self.view addSubview:jiaortview];
    [jiaortview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(imgrt.size);
        make.right.equalTo(self.view).mas_offset(-40 + 2.5);
        //height / 2 - width / 2 + 40 - 2.5
        make.top.equalTo(self.view).mas_offset(height / 2 - width / 2 + 40 - 2.5);
    }];
    [self.view addSubview:jiaoltview];
    [jiaoltview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(imgrt.size);
        make.left.equalTo(self.view).mas_offset(40 - 2.5);
        make.top.equalTo(jiaortview);
    }];
    [self.view addSubview:jiaolbview];
    [jiaolbview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(imgrt.size);
        make.left.equalTo(jiaoltview);
        make.bottom.equalTo(self.view).mas_offset(-(height / 2 - width / 2 + 40 - 2.5));
    }];
    [self.view addSubview:jiaorbview];
    [jiaorbview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(imgrt.size);
        make.bottom.equalTo(jiaolbview);
        make.right.equalTo(jiaortview);
    }];
    UILabel *lab =[[UILabel alloc]init];
    [self.view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(jiaorbview.mas_bottom).offset(10);
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
    }];
    lab.text =@"扫描设备上的二维码";
    lab.textColor =[UIColor whiteColor];
    lab.textAlignment=NSTextAlignmentCenter;
    lab.font=F(12);
    
    if (self.dataType==HasListData) {
        self.view.userInteractionEnabled=YES;
        UIImage *leftImg=[UIImage imageNamed:@"Ico_scan_add"];
        UIImage *rightImg=[UIImage imageNamed:@"Ico_scan_search"];
        UIButton *leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:leftButton];
        [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lab.mas_bottom).offset(20);
            make.left.equalTo(self.view).offset(40);
            make.width.equalTo(@(100));
            make.height.equalTo(@(100));
            
        }];
       
        UIImageView *leftImgView=[[UIImageView alloc]initWithFrame:CGRectMake((100-leftImg.size.width)/2, 0, leftImg.size.width, leftImg.size.height)];
        [leftButton addSubview:leftImgView];
        leftImgView.image=leftImg;
        UILabel *leftLab =[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(leftImgView.frame)+10, 100, 20)];
        [leftButton addSubview:leftLab];

        leftLab.text =@"手动输入";
        leftLab.textAlignment=NSTextAlignmentCenter;
        leftLab.textColor=[UIColor whiteColor];
        leftLab.font=F(12);
        [leftButton bk_addEventHandler:^(id sender) {
            EquipmentViewController *equipVc=[[EquipmentViewController alloc]init];
            equipVc.orderUuid=self.orderUuid;
            equipVc.num=self.num;
            equipVc.instUuid=self.instUuid;
            //有单
            [self pushController:equipVc Lever:1 Animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];


        UIButton *rightButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:rightButton];
        [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lab.mas_bottom).offset(20);
            make.right.equalTo(self.view.mas_right).offset(-40);
            make.width.equalTo(@(100));
            make.height.equalTo(@(100));
            
        }];
        [rightButton bk_addEventHandler:^(id sender) {
            SeekEquipmentViewController *equipVc=[[SeekEquipmentViewController alloc]init];
            equipVc.orderUuid=self.orderUuid;
            equipVc.instUuid=self.instUuid;
            equipVc.num=self.num;
            //有单
            [self pushController:equipVc Lever:1 Animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
        UIImageView *rightImgView=[[UIImageView alloc]initWithFrame:CGRectMake((100-leftImg.size.width)/2, 0, rightImg.size.width, rightImg.size.height)];
        [rightButton addSubview:rightImgView];
        rightImgView.image=rightImg;

       
        UILabel *rightLab =[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(rightImgView.frame)+10, 100, 20)];
        [rightButton addSubview:rightLab];
        rightLab.text =@"查找";
        rightLab.textAlignment=NSTextAlignmentCenter;
        rightLab.textColor=[UIColor whiteColor];
        rightLab.font=F(12);
     
    }else
    {
        
    }
}


- (void)initScan{

    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

//    }
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
        return;
    } else{
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        //创建AVCaptureDeviceInput    输入设备为手机摄像头
        _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
        //创建AVCaptureMetadataOutput设置好扫描成功回调代理以及回调线程
        _output = [[AVCaptureMetadataOutput alloc] init];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        _session = [[AVCaptureSession alloc] init];
        //高质量采集
        [_session setSessionPreset:AVCaptureSessionPresetHigh];
        if ([_session canAddInput:_input]) {
            [_session addInput:_input];
        }
        if ([_session canAddOutput:_output]) {
            [_session addOutput:_output];
            
        }
        
        _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
        UIView *scanView = self.view;
        
        _preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
        _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _preview.frame = scanView.layer.bounds;
        [scanView.layer insertSublayer:_preview atIndex:0];
 
    }
    
    }

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}

- (void) start{
    float width = [UIScreen mainScreen].bounds.size.width;
    float height = [UIScreen mainScreen].bounds.size.height;
    [_lineView setHidden:NO];
    [_lineView setFrame:CGRectMake(40, height / 2 - width / 2 + 40, width - 80, 2)];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(lineMove) userInfo:nil repeats:YES];
    
    CGSize size = CGSizeMake(MAX(width, height), MAX(width, height));
    CGRect rect = CGRectMake(1.0 / 2 - size.height / height / 2, 1.0 / 2 - size.width / width / 2, size.height / height, size.width / width);
    //rectOfInterest  这个属性用来限制扫描范围。这个属性的每一个值取值范围在0~1之间，代表的是对应轴上的比例大小
    [_output setRectOfInterest:rect];
    [_session startRunning];
}

- (void) lineMove{
    CGRect frame = _lineView.frame;
    frame.origin.y += 1;
    
    float width = [UIScreen mainScreen].bounds.size.width;
    float height = [UIScreen mainScreen].bounds.size.height;
    if (frame.origin.y >= height - (height / 2 - width / 2 + 40) - _lineView.frame.size.height) {
        frame.origin.y = height / 2 - width / 2 + 40;
    }
    [_lineView setFrame:frame];
}
//来获取扫描得到的数据
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    NSString *stringValue;
    if ([metadataObjects count] > 0) {
        [_session stopRunning];
        [_timer invalidate];
        _timer = nil;
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        if ([stringValue hasPrefix:WebURL]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringValue]];
            return;
        }
        
//        NSLog(@"stringValue========%@",stringValue);
        //equipController 扫码信息
        NSDictionary *infoDic= [Common dictionaryWithJsonString:stringValue];
        if (![[infoDic objectForKey:@"appkey"]isEqualToString:@"LittleBitDimension"]) {
            [CClass showMessage:@"该二维码不属于邮易维" completion:^{
                [self backController];
                
            }];
            return;
        }
        NSMutableDictionary *data =[[NSMutableDictionary alloc]init];
        [data setObject:[infoDic objectForKey:@"uuid"] forKey:@"uuid"];
        ///从有报账单时候
        if (self.dataType==HasListData) {
           
            [CClass HttpRequestTask:YES withUrl:@"machine_detail" withData:data notifyError:YES onSuccess:^(BaseModel *model) {
                NSString *state=[model.B_data objectForKey:@"status"];
                NSString *blank=[model.B_data objectForKey:@"is_blank"];
                //status,1为失效，0为有效   is_blank 1:不是空白设备。0：空白设备
                    //有效，不为空的
                if ([state isEqualToString:@"0"]) {
                    
                    //扫码之后进入详情界面
                    HistoryViewController *historyVC =[[HistoryViewController alloc]init];
                    historyVC.machineUuid=[infoDic objectForKey:@"uuid"];
                    historyVC.orderUuid=self.orderUuid;
                    historyVC.num=self.num;
                    historyVC.Type=MachineUnLink;//需要关联
                    [self pushController:historyVC Lever:1 Animated:YES];
                    
                }else
                {
                    //失效的
                    [CClass showMessage:@"该二维码已失效" completion:^{
                        [self backController];}];
                }
                
                
                
                
            } onError:^(BaseModel *model) {
                
            }];

            
            
        }else if(self.dataType==NoListdata)
        {
            ///从无单子跳过来
            //二维码的uiuid
            NSMutableDictionary *data =[[NSMutableDictionary alloc]init];
            [data setObject:[infoDic objectForKey:@"uuid"] forKey:@"uuid"];
            [CClass HttpRequestTask:YES withUrl:@"machine_detail" withData:data notifyError:YES onSuccess:^(BaseModel *model) {
                NSString *state=[model.B_data objectForKey:@"status"];
                NSString *blank=[model.B_data objectForKey:@"is_blank"];
                //status,1为失效，0为有效   is_blank 1:不是空白设备。0：空白设备
                //有效，不为空的
                if ([state isEqualToString:@"0"]) {
                    
                    //扫码之后进入详情界面
                    HistoryViewController *historyVC =[[HistoryViewController alloc]init];
                    historyVC.machineUuid=[infoDic objectForKey:@"uuid"];
                    historyVC.num=1000;
                    historyVC.orderUuid=@"";
                    historyVC.Type=MachineLink;//不需要关联
                    [self pushController:historyVC Lever:1 Animated:YES];

                }else
                {
                    //失效的
                    [CClass showMessage:@"该二维码已失效" completion:^{
                        [self backController];}];
                }

                
            } onError:^(BaseModel *model) {
                
            }];
           
        }
        
 
    }

   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //模拟器
    if (TARGET_IPHONE_SIMULATOR)
    {
        echo(@"模拟器");
    }else
    {
        if (_session == nil) {
            [self initScan];
        }
        [self start];
    }
   
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_session stopRunning];
    [_session removeInput:_input];
    [_session removeOutput:_output];
    _session = nil;
    _preview = nil;
    _output = nil;
    _input = nil;
    _device = nil;
    [_timer invalidate];
    _timer = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
